﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UserSyncService
{
    public static class Common
    {
        /* 获取 utc 1970-1-1到现在的秒数 */
        public static long Get1970ToNowSeconds()
        {
            return (System.DateTime.UtcNow.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
        }
        /* 获取 utc 1970-1-1到现在的毫秒数 */
        public static long Get1970ToNowMilliseconds()
        {
            return (System.DateTime.UtcNow.ToUniversalTime().Ticks - 621355968000000000) / 10000;
        }
        public static string GetMD5(string str)
        {
            byte[] b = System.Text.Encoding.Default.GetBytes(str);

            b = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(b);
            string ret = "";
            for (int i = 0; i < b.Length; i++)
            {
                ret += b[i].ToString("x").PadLeft(2, '0');
            }
            return ret;
        }

        public static string GetConfigString(string key, string @default = "")
        {
            return ConfigurationManager.AppSettings[key] ?? @default;
        }

        /// <summary>
        /// json字符串转化为相应的类型
        /// </summary>
        /// <typeparam name="T">转化后的类型</typeparam>
        /// <param name="json">json字符串</param>
        /// <returns>转化后的类型</returns>
        public static T ToObject<T>(this string json)
        {
            return json == null ? default(T) : JsonConvert.DeserializeObject<T>(json);
        }

        /// <summary>
        /// json字符串转化为对应的类型列表
        /// </summary>
        /// <typeparam name="T">转化后的类型</typeparam>
        /// <param name="json">json字符串</param>
        /// <returns>List<T></returns>
        public static List<T> ToList<T>(this string json)
        {
            return json == null ? null : JsonConvert.DeserializeObject<List<T>>(json);
        }
    }
}
